<?php
/**
 *
 * 验证码 控制器
 */
class Captcha extends MY_Controller
{
    public function index()
    {
        // $this->generate();
    }
    
    
    public function generate($uuid)
    {
        $this->load->helper('captcha');
        if(!$uuid){
            return;
        }
        $vals = array(
            'img_path'  => './files/captcha/',
            'img_url'   => 'http://localhost:8012/files/captcha/',
            'img_width' => '66',
            'img_height'    => 30,
            'expiration'    => 7200,
            'word_length'   => 4,
            'font_size' => 20,
            'img_id'    => 'Imageid',
            'pool'      => '0123456789',
            // 'pool'      => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'colors'    => array(
                'background' => array(255, 255, 255),
                'border' => array(255, 255, 255),
                // 'border' => array(19, 169, 169),
                'text' => array(0, 0, 0),
                'grid' => array(255, 245, 240)
            )
        );

        $cap = create_captcha($vals);
        
    //    $this->send($cap);
    //     return;
       if($this->saveDb($cap,$uuid)){
        //    $base64_data = base64_encode( imagepng($cap['image']));
        //    $base64Data = 'data:png;base64,'.$base64_data;
        //    $this->send($base64Data);
       }
        // echo 'Submit the word you see below:';
        // echo $cap['image'];
        // echo '<input type="text" name="captcha" value="" />';
        // // ----------------------------------- // Generate the image // -----------------------------------
        header('Content-Type: image/png');
        echo imagepng($cap['image']);
    }

    /* 保存到数据库 */
    private function saveDb($cap,$uuid)
    {
        $data = array(
            'ip_address'    => $this->input->ip_address(),
            'word'      => $cap['word'],
            'cap_uuid'    => $uuid,
        );
        
        $this->load->entity('sys/EntityCaptcha','entity_cap');
        $valid = $this->entity_cap->valid(null,$data);
        if($valid['result']){
            $query = $this->db->insert_string('sys_captcha', $data);
            return $this->db->query($query);
        }else{
            $this->send($valid['error'],50100);
            return false;
        }
    }
}
